#!/usr/bin/perl
#
# Copyright (c) 2020 NVI, Inc.
#
# This file is part of VLBI Field System
# (see http://github.com/nvi-inc/fs).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

#
use Time::HiRes qw( usleep);

open(my $pipe, '-|', '/sbin/ifconfig') or die $!;
while (my $line = <$pipe>) {
#    print "start: $line";
    if($line =~ /^([^ ]+)/) {
        $intf=$1;
    } elsif($line =~ /^ +RX bytes[^\d ]*(\d+)/) {
	$bytes{0}{$intf}=$1;
    }
}

$slept=usleep(250000);
if($slept < 100000) {
    print "sleep too short: ", $slept*1e-6," seconds\n";
    exit;
}

open(my $pipe, '-|', '/sbin/ifconfig') or die $!;
while (my $line = <$pipe>) {
    if($line =~ /^([^ ]+)/) {
        $intf=$1;
    } elsif($line =~ /^ +RX bytes[^\d ]*(\d+)/) {
	$bytes{1}{$intf}=$1;
    }
}
$fact=8e-9/(1e-6*$slept);
foreach $key (sort(keys %{ $bytes{0}})) {
    if($key ne "eth0" && $key ne "lo" && $key ne "eth1") {
	if(!defined($bytes{1}{$key})) {
	    print "second measurement missing interface $key\n";
	    exit;
	}
    }
}
foreach $key (sort(keys %{ $bytes{1}})) {
    if($key ne "eth0" && $key ne "lo" && $key ne "eth1") {
	if(!defined($bytes{0}{$key})) {
	    print "first measurement missing interface $key\n";
	    exit;
	}
    }
}
foreach $key (sort(keys %{ $bytes{1}})) {
    if($key ne "eth0" && $key ne "lo" && $key ne "eth1") {
        print "$key ";
        printf "%.3f",$fact*($bytes{1}{$key}-$bytes{0}{$key});
        print " ";
    }
}
print "Gb/s\n";
